package com.duang.netty.agreement.utils;

import io.netty.buffer.ByteBuf;
import org.jboss.marshalling.Marshaller;

import java.io.IOException;
//netty消息编码工具类
public class MarshallingEncoder {
    private static final byte[] LENGTH_PLACEHOLDER  = new byte[4];
    Marshaller marshaller;

    public MarshallingEncoder() throws IOException {
        marshaller = MarshallingCodecFactory.buildMarshalling();
    }
    public void encode(Object msg, ByteBuf out) throws Exception {
        try{
            int lengthPos = out.writerIndex();
            out.writeBytes(LENGTH_PLACEHOLDER);//对象长度
            ChannelBufferByteOutput output = new ChannelBufferByteOutput(out);
            marshaller.start(output);
            marshaller.writeObject(msg);
            marshaller.finish();
            out.setInt(lengthPos,out.writerIndex()-lengthPos-4);//对象字节流长度    写后-写之前-对象长度
        }finally {
            marshaller.close();
        }

    }
}
